package com.travel.search.service.Impl;

import com.alibaba.fastjson.JSON;
import com.travel.common.es.AttractionEsModel;
import com.travel.search.config.TravelElasticsearchConfig;
import com.travel.search.constant.EsConstant;
import com.travel.search.service.AttractionSaveService;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.bulk.BulkItemResponse;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
public class AttractionSaveServiceImpl implements AttractionSaveService {

    @Autowired
    RestHighLevelClient restHighLevelClient;

    /**
     * 保存景点到es中
     *
     * @param attractionEsModel
     * @return
     */
    @Override
    public boolean attractionSave(AttractionEsModel attractionEsModel) throws IOException {
        //1.给es中建立索引，建立映射关系

        //2.给es中保存这些数据
        BulkRequest bulkRequest = new BulkRequest();
        //2.1 构造请求保存
        IndexRequest indexRequest = new IndexRequest(EsConstant.PRODUCT_INDEX);
        indexRequest.id(attractionEsModel.getAttractionId().toString());
        String s = JSON.toJSONString(attractionEsModel);
        indexRequest.source(s, XContentType.JSON);

        //2.2 把多条保存操作放入一个bulkRequest中 统一保存
        bulkRequest.add(indexRequest);

        BulkResponse bulk = restHighLevelClient.bulk(bulkRequest, TravelElasticsearchConfig.COMMON_OPTIONS);


        //b：是否有异常 true：有 false：无
        boolean b = bulk.hasFailures();

        return b;

    }
}
